<template>
  <div >
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="任务编码" prop="taskNo" label-width="90px">
        <el-input
          v-model="queryParams.taskNo"
          placeholder="请输入任务编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接收方名称" prop="taxCompanyName" label-width="90px">
        <el-input
          v-model="queryParams.taxCompanyName"
          placeholder="请输入接收方名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleTaxPointOpen"
        >批量开票</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="table" v-loading="loading" :data="invoiceList"  @select="handleSelectionChange" @select-all="handleSelectionAllChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="任务编码" align="center" prop="taskNo" show-overflow-tooltip min-width="150"/>
      <el-table-column label="任务名称" align="center" prop="task.taskName" show-overflow-tooltip min-width="150"/>
      <el-table-column label="接收方" align="center" prop="taxCompanyName" min-width="200"/>
      <el-table-column label="开票类型" align="center" prop="isInvoicing" width="100">
        <template slot-scope="{ row }">
          <el-tag style="cursor: pointer">专票</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开票类目" align="center" prop="invoiceCatagory" min-width="220">
        <template slot-scope="{ row }">
           <span v-if="organizationType === 1">
              信息技术服务*信息技术服务费
          </span>
          <span v-else-if="organizationType === 2">
            现代服务*推广服务费
          </span>
        </template>
      </el-table-column>
      <el-table-column label="下发金额" align="center" prop="successAmount" width="140">
        <template slot-scope="{ row }">
          {{row.amount}}
        </template>
      </el-table-column>
      <el-table-column label="分润金额" align="center" prop="successMerchantAmount" width="140">
        <template slot-scope="{ row }">
          {{row.separateAmount}}元
        </template>
      </el-table-column>
      <el-table-column label="分润费率" align="center" prop="successAmount" min-width="100">
        <template slot-scope="{ row }">
          {{row.separateRate}}%
        </template>
      </el-table-column>
      <el-table-column label="开票时间" align="center" prop="createTime" width="180"></el-table-column>
      <el-table-column fixed="right" width="150" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleInvoice(scope.row)"
          >开票/详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :close-on-click-modal="false" @close="form.taxPoint = null" :close-on-press-escape="false" title="批量开票" :visible.sync="taxPointOpen" width="500px" destroy-on-close append-to-body>
      <el-select v-model="form.taxPoint" placeholder="请选择税点" clearable >
        <el-option label="1%" :value="1"></el-option>
        <el-option label="3%" :value="3"></el-option>
        <el-option label="6%" :value="6"></el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="invoiceLoading" type="primary" @click="handleAllTaxPoint">立即开票</el-button>
        <el-button :loading="invoiceLoading" @click="taxPointOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer :wrapperClosable="false" :close-on-press-escape="false" title="批量开票" :visible.sync="invoiceAllOpen" size="65%" destroy-on-close append-to-body>
      <el-row :gutter="20">
        <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
          <pane size="28">
            <el-col>
              <div class="head-container">
              </div>
              <div class="head-container">
                <el-tree highlight-current t @node-click="handleNodeClick" :default-expanded-keys="defaultExpandedKeys" :data="subInvoice" ref="tree" node-key="key">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                       <span v-if="node.level === 1">{{ data.taxCompanyName }}</span>
                    </span>
                </el-tree>
              </div>
            </el-col>
          </pane>
          <pane size="72">
            <el-col>
              <el-descriptions border title="开票信息">
                <el-descriptions-item label="开票发票类型">{{invoiceInfo.invoiceType===1?'专票':invoiceInfo.invoiceType===2?'普票':''}}</el-descriptions-item>
                <el-descriptions-item :span="2" label="开票类目">{{ invoiceInfo.invoiceCatagory }}</el-descriptions-item>

                <el-descriptions-item label="下发金额">{{ formattedTotal(invoiceInfo.amount) }}</el-descriptions-item>
                <el-descriptions-item label="下发服务费" >{{ formattedTotal(invoiceInfo.separateAmount) }}</el-descriptions-item>

                <el-descriptions-item label="税额/%">{{ invoiceInfo.taxPoint+"%" }}</el-descriptions-item>
                <el-descriptions-item label="税额/元">{{ formattedTotal(invoiceInfo.taxAmount) }}</el-descriptions-item>
                <el-descriptions-item label="不含税金额/元">{{ formattedTotal(invoiceInfo.taskAmount) }}</el-descriptions-item>
                <el-descriptions-item label="价税合计/元">{{ formattedTotal(invoiceInfo.invoiceAmount) }}</el-descriptions-item>
              </el-descriptions>

              <el-row :gutter="10" class="mb8 mb8-s">
                <el-col :span="1.5">
                  <el-button
                    type="warning"
                    plain
                    icon="el-icon-more-outline"
                    size="mini"
                    v-if="!invoiceInfo.status"
                    @click="handleInvoicing"
                  >开票</el-button>
                </el-col>
              </el-row>
              <el-table :data="invoiceInfo.separates" max-height="500" :summary-method="getSummaries" show-summary>
                <el-table-column label="任务编码" align="center" prop="taskNo" min-width="180" />
                <el-table-column label="任务名称" align="center" prop="taskName" min-width="180" />
                <el-table-column label="下发金额" align="center" prop="amount" min-width="100">
                  <template slot-scope="{ row }">
                    {{ row.amount ? row.amount : 0 }}元
                  </template>
                </el-table-column>

                <el-table-column label="下发服务费" align="center" prop="separateAmount" min-width="100">
                  <template slot-scope="{ row }">
                    {{ row.separateAmount ? row.separateAmount : 0 }}元
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </pane>
        </splitpanes>
      </el-row>
<!--      <div class="dialog-footer-all">-->
<!--        <el-button :loading="invoiceLoading" type="primary" @click="submitInvoiceAll">立即提交</el-button>-->
<!--        <el-button :loading="invoiceLoading" @click="invoiceOpen = false">取 消</el-button>-->
<!--      </div>-->
    </el-drawer>

    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="开票" :visible.sync="invoiceOpen" width="500px" destroy-on-close append-to-body>
      <el-form ref="invoiceForm" v-loading="invoiceLoading" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="税点" prop="taxPoint">
          <el-select v-model="form.taxPoint" placeholder="请选择税点" clearable @change="handleTaxPoint">
            <el-option label="1%" :value="1"></el-option>
            <el-option label="3%" :value="3"></el-option>
            <el-option label="6%" :value="6"></el-option>
          </el-select>
        </el-form-item>
        <el-collapse-transition>
          <div v-show="form.taxPoint">
            <el-form-item label="税额/元">
              {{ formattedTotal(form.taxAmount) }}
            </el-form-item>
            <el-form-item label="不含税金额/元">
              {{ formattedTotal(form.taskAmount) }}
            </el-form-item>
            <el-form-item label="价税合计/元">
              {{ formattedTotal(form.invoiceAmount) }}
            </el-form-item>
            <el-form-item label="接收方">
              {{ form.taxCompanyName }}
            </el-form-item>
            <el-form-item label="纳税识别号">
              {{ form.taxCreditCode }}
            </el-form-item>
            <el-form-item label="开票类型">
              <el-tag style="cursor: pointer">专票</el-tag>
            </el-form-item>
            <el-form-item label="开票类目">
            <span v-if="organizationType === 1">
                信息技术服务*信息技术服务费
            </span>
            <span v-else-if="organizationType === 2">
              现代服务*推广服务费
            </span>
            </el-form-item>
            <el-form-item label="发票" prop="invoiceFile">
              <FileUpload :file-type='["pdf","zip","png", "jpg", "jpeg"]' v-model="form.invoiceFile" :limit="1"
              ></FileUpload>
            </el-form-item>
          </div>
        </el-collapse-transition>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="invoiceLoading" type="primary" @click="submitInvoice">立即开票</el-button>
        <el-button :loading="invoiceLoading" @click="invoiceOpen = false">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="开票" :visible.sync="invoicingOpen" width="500px" destroy-on-close append-to-body>
      <el-form ref="invoiceForm" v-loading="invoiceLoading" :model="invoiceInfo" :rules="rules" label-width="100px">
        <el-form-item label="税点/%">
          {{ invoiceInfo.taxPoint }}
        </el-form-item>
          <el-form-item label="税额/元">
            {{ formattedTotal(invoiceInfo.taxAmount) }}
          </el-form-item>
          <el-form-item label="不含税金额/元">
            {{ formattedTotal(invoiceInfo.taskAmount) }}
          </el-form-item>
          <el-form-item label="价税合计/元">
            {{ formattedTotal(invoiceInfo.invoiceAmount) }}
          </el-form-item>
          <el-form-item label="接收方">
            {{ invoiceInfo.taxCompanyName }}
          </el-form-item>
          <el-form-item label="纳税识别号">
            {{ invoiceInfo.taxCreditCode }}
          </el-form-item>
          <el-form-item label="开票类型">
            <el-tag style="cursor: pointer">专票</el-tag>
          </el-form-item>
          <el-form-item label="开票类目">
          <span v-if="organizationType === 1">
              信息技术服务*信息技术服务费
          </span>
            <span v-else-if="organizationType === 2">
            现代服务*推广服务费
          </span>
          </el-form-item>
          <el-form-item label="发票" prop="invoiceFile">
            <FileUpload :file-type='["pdf","zip","png", "jpg", "jpeg"]' v-model="invoiceInfo.invoiceFile" :limit="1"
            ></FileUpload>
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="invoiceLoading" type="primary" @click="submitInvoiceAll">立即开票</el-button>
        <el-button :loading="invoiceLoading" @click="invoicingOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import store from '@/store'
import 'splitpanes/dist/splitpanes.css'
import {Pane, Splitpanes} from "splitpanes";
import { listSeparate } from '@/api/transfer/separate'
import { submitPayslipInvoice ,submitPayslipInvoiceAll } from '@/api/invoice/invoice'
export default {
  name: 'pending0',
  components: { Splitpanes, Pane },
  data(){
    return{
      loading:false,
      total:0,
      tslList:[],
      showSearch:true,
      invoiceInfo:{},
      taxPointOpen:false,
      invoicingOpen:false,
      invoiceOpen:false,
      invoiceAllOpen:false,
      invoiceLoading:false,
      invoiceList:[],
      subInvoice:[],
      selectedRowKeys:[],
      queryParams:{
        pageNum: 1,
        pageSize: 10,
        taskNo:null,
        isInvoicing:0,
        status:2,
        taxCompanyName:null,
      },
      tslName:null,
      form:{},
      defaultExpandedKeys:[],
      organizationType: store.getters.organizationType,
      rules:{
        taxPoint:[
          { required: true, message: "请选择税点", trigger: "change" }
        ],
        invoiceFile:[
          { required: true, message: "请上传发票", trigger: "change" }
        ]
      }
    }
  },
  mounted() {
    this.getList()
  },
  created() {
    this.selectedRowKeys = []
    this.subInvoice = []
  },
  methods:{
    getList() {
      this.loading = true
      listSeparate(this.queryParams).then(response => {
        this.invoiceList = response.rows
        this.total = response.total
        this.loading = false
        this.setSelected()

      }).catch(() => {
        this.loading = false
      })
    },
    setSelected() {
      this.invoiceList.forEach(item => {
        const isSelected = this.selectedRowKeys.find(row => item.separateId === row.separateId)
        item._selected = isSelected
        if (isSelected) {
          this.$nextTick(() => {
            this.$refs.table.toggleRowSelection(item, isSelected)
          })
        }
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.subInvoice = []
      this.selectedRowKeys = []
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    handleInvoice(row) {
      this.form = row
      this.form.invoiceType = 1
      this.form.organizationType = 3
      this.form.separate = {
        isInvoicing:2,
        separateId:this.form.separateId,
      }
      if (this.organizationType === 1){
        this.form.invoiceCatagory = "信息技术服务*信息技术服务费"
      }else if (this.organizationType === 2){
        this.form.invoiceCatagory = "现代服务*推广服务费"
      }
      this.form.receiverOrganizationId = this.form.taxOrganizationId
      this.invoiceOpen = true
    },

    submitInvoice() {
      this.$refs["invoiceForm"].validate(valid => {
        if (valid) {
          this.$modal.confirm('确定要提交这些任务吗？').then(() => {
            this.invoiceLoading = true
            submitPayslipInvoice(this.form).then(res => {
              this.invoiceLoading = false
              this.invoiceOpen = false
              this.getList()
            }).catch(() => {
              this.invoiceLoading = false
            })
          })
        }
      })
    },

    handleTaxPointOpen(){
      if (this.subInvoice.length === 0){
        this.$message.warning("请选择列表数据");
        return;
      }
      this.taxPointOpen = true
    },

    handleNodeClick(v,d) {
      this.invoiceInfo = v
    },

    handleSelectionChange(selection, row) {
      const isAdd = selection.some((selectRow) => selectRow.separateId === row.separateId)
      if (isAdd) {
        if (this.selectedRowKeys.length >= 1000) {
          this.$message.warning('最多选择1000条')
        }
      }
      this.handleRowChangeAll(row, isAdd)
    },
    handleSelectionAllChange(selection) {
      let isAdd = true
      let changeSelect = selection.slice()

      if (!changeSelect.length) {
        isAdd = false
        changeSelect = this.invoiceList.slice()
      }
      if (isAdd) {
        if (this.selectedRowKeys.length >= 1000) {
          this.$message.warning('最多选择1000条')
        }
      }

      for (let i = 0; i < changeSelect.length; i++) {
        const row = changeSelect[i]
        // 检查是否应该终止循环
        this.handleRowChangeAll(row, isAdd)
      }
    },
    handleRowChangeAll(row, isAdd) {
      const index = this.selectedRowKeys.findIndex(
        item => item.separateId === row.separateId
      )
      let taskAmount = row.successAmount + row.successMerchantAmount
      if (!taskAmount) {
        taskAmount = 0
      }
      if (index === -1) {
        if (isAdd) {
          // 预检查添加后的数量
          if (this.selectedRowKeys.length >= 1000) {
            this.$refs.table.toggleRowSelection(row, false)
          } else {

            // 查找或创建发票记录
            let subInvoice = this.subInvoice.find(item => item.receiverOrganizationId === row.taxOrganizationId)
            if (!subInvoice) {
              subInvoice = {
                organizationType:3,
                amount:row.amount,
                invoiceType:1,
                separateAmount:row.separateAmount,
                taxCompanyName: row.taxCompanyName,
                taxCreditCode:row.taxCreditCode,
                invoiceCatagory: this.organizationType === 1?"信息技术服务*信息技术服务费":"现代服务*推广服务费",
                initiatorOrganizationId:row.organizationId,
                receiverOrganizationId:row.taxOrganizationId,
                key:row.taxOrganizationId+row.taxCompanyName,
                separates:[{
                  amount:row.amount,
                  taskNo:row.task.taskNo,
                  taskName:row.task.taskName,
                  separateId:row.separateId,
                  separateRate:row.separateRate,
                  separateAmount:row.separateAmount,
                }],
              }
              this.subInvoice.push(subInvoice)
            }else{
              subInvoice.organizationType=3;
              subInvoice.taxCompanyName= row.taxCompanyName;
              subInvoice.initiatorOrganizationId=row.organizationId;
              subInvoice.receiverOrganizationId=row.taxOrganizationId;
              subInvoice.key = row.taxOrganizationId+row.taxCompanyName;
              subInvoice.amount = subInvoice.amount + row.amount;
              subInvoice.separateAmount = subInvoice.separateAmount +row.separateAmount;
              subInvoice.separates.push({
                amount:row.amount,
                taskNo:row.task.taskNo,
                taskName:row.task.taskName,
                separateId:row.separateId,
                separateRate:row.separateRate,
                separateAmount:row.separateAmount,
              })
            }
            this.selectedRowKeys.push({ separateId: row.separateId })
          }
        }
      } else {
        if (!isAdd) {
          // 从选中行列表中移除
          const index = this.selectedRowKeys.findIndex(item => item.separateId === row.separateId);
          if (index !== -1) {
            this.selectedRowKeys.splice(index, 1);
          }

          let subInvoiceIndex = this.subInvoice.findIndex(item => item.receiverOrganizationId === row.taxOrganizationId)
          if (subInvoiceIndex !== -1) {
            this.subInvoice[subInvoiceIndex].amount = parseFloat(this.subInvoice[subInvoiceIndex].amount) - parseFloat(row.amount);
            this.subInvoice[subInvoiceIndex].separateAmount = parseFloat(this.subInvoice[subInvoiceIndex].separateAmount) - parseFloat(row.separateAmount);


            let separateIndex = this.subInvoice[subInvoiceIndex].separates.findIndex(item => item.separatesId === row.separatesId)
            if (separateIndex !== -1){
              this.subInvoice[subInvoiceIndex].separates.splice(separateIndex, 1);
            }
            if (this.subInvoice[subInvoiceIndex].amount <= 0 || this.subInvoice[subInvoiceIndex].separateAmount <= 0){
              this.subInvoice.splice(subInvoiceIndex, 1);
            }
          }
        }
      }
      return false
    },


    // 准备分类数据（分离关注点）
    handleAllTaxPoint() {
      this.invoiceLoading = true
      let taxRate = this.form.taxPoint
      this.subInvoice.forEach((item) => {
        item.taxPoint = taxRate;
        // 金额转换为分（避免浮点精度问题）
        item.invoiceAmount = this.toInteger(item.separateAmount);

      // 计算不含税金额和税额（使用整数运算）
        const divisor = 100 + taxRate;

      // 计算不含税金额 (Y) - 使用分作为单位进行计算
        item.taskAmount = Math.round(item.invoiceAmount * 100 / divisor);

        // 计算税额 - 使用分作为单位
        item.taxAmount = item.invoiceAmount - item.taskAmount;

        // 转回元为单位（显示用）
        item.invoiceAmount = item.invoiceAmount / 100;
        item.taskAmount = item.taskAmount / 100;
        item.taxAmount = item.taxAmount / 100;

      })
      this.taxPointOpen = false
      this.invoiceAllOpen = true
      this.handleNodeClick( this.subInvoice[0])
      this.$nextTick(() => {
        this.defaultExpandedKeys = [this.subInvoice[0]]
        this.$refs.tree.setCurrentNode(this.subInvoice[0])
      })
      this.invoiceLoading = false
    },

    submitInvoiceAll(){
      this.$refs["invoiceForm"].validate(valid => {
        if (valid) {
          this.$modal.confirm('确定要提交这些任务吗？').then(() => {
            this.invoiceLoading = true
            submitPayslipInvoiceAll(this.invoiceInfo).then(res => {
              this.invoiceLoading = false
              this.invoicingOpen = false
              this.invoiceInfo.status = 2


              let subInvoiceIndex = this.subInvoice.findIndex(item => item.receiverOrganizationId === this.invoiceInfo.taxOrganizationId)
              this.subInvoice.splice(subInvoiceIndex, 1);

              this.getList()
            }).catch(() => {
              this.invoiceLoading = false
            })
          })
        }
      })
    },

    handleInvoicing(){
      this.invoicingOpen = true
    },


    /** 导出按钮操作 */
    handleExport() {

      this.download('invoice/invoice/export', {
        ...this.queryParams
      }, `待开票_${new Date().getTime()}.xlsx`)
    },
    handleTaxPoint(taxRate){
      this.invoiceLoading = true
      // 金额转换为分（避免浮点精度问题）
      this.form.invoiceAmount = this.toInteger(this.form.separateAmount);

// 计算不含税金额和税额（使用整数运算）
      const divisor = 100 + taxRate;

// 计算不含税金额 (Y) - 使用分作为单位进行计算
      this.form.taskAmount = Math.round(this.form.invoiceAmount * 100 / divisor);

  // 计算税额 - 使用分作为单位
      this.form.taxAmount = this.form.invoiceAmount - Math.round(this.form.taskAmount / 100);

  // 转回元为单位（显示用）
      this.form.invoiceAmount = this.form.invoiceAmount / 100;
      this.form.taskAmount = this.form.taskAmount / 100;
      this.form.taxAmount = this.form.taxAmount / 100;

      this.invoiceLoading = false
    },
    formattedTotal(amount) {
      if (!amount){
        return "￥0";
      }
      const formatter = new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })

      return formatter.format(amount)
    },
    // 辅助方法：转换为整数（处理金额）
    toInteger(value) {
      if (typeof value === 'number') return Math.round(value * 100)
      if (typeof value === 'string') return Math.round(parseFloat(value) * 100)
      return 0
    },
    getSummaries(param){
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
        }else if (column.property === "amount" || column.property === "separateAmount" ) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                const result = prev + curr;
                return parseFloat(result.toFixed(2));
              } else {
                return prev;
              }
            }, 0);
            sums[index] += ' 元';
          } else {
            sums[index] = 'N/A';
          }
        }

      });

      return sums;
    },
  },
  watch: {

  }
}
</script>

<style lang="scss" scoped>
.infinite-list-wrapper {
  max-height: calc(100vh - 180px);
}
.invoiceTaskQueryClass{
  margin-top: 20px;
}
::v-deep .el-drawer__body{
  padding: 0 20px;
}
.dialog-footer-all{
  left: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  height: 55px;
  padding: 10px 20px;
  position: absolute;
  justify-content: flex-end;
  background-color: #ffffff;
  box-shadow: 0 0 4px rgba(0, 21, 41, 0.35);
}
.mb8-s{
  margin-top: 10px;
}
</style>
